package com.example.pay.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.diagnosis.DiagnosisUtils;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.example.pay.config.AliPayProperties;
import com.example.pay.domain.dto.PayDTO;
import com.example.pay.domain.po.Order;
import com.example.pay.mapper.OrderMapper;
import com.example.pay.service.PaymentService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;


@Service
@RequiredArgsConstructor
public class AliPay implements PaymentService {
    private final AliPayProperties aliPayProperties;
    private final OrderMapper orderMapper;

    // 在AliPay类中添加新的返回数据结构
    @Override
    public Object processPayment(PayDTO payDTO) {
        try {
            AlipayClient alipayClient = new DefaultAlipayClient(getAlipayConfig());

            // 构造请求参数以调用接口
            AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
            AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
            Long orderId = payDTO.getOrderId();
            // 设置商户订单号
            model.setOutTradeNo(orderId.toString());

            // 设置订单总金额
            model.setTotalAmount(payDTO.getPayMoney().toString());

            // 设置订单标题
            model.setSubject(payDTO.getSubject());

            // 设置产品码
            model.setProductCode("QUICK_MSECURITY_PAY");

            request.setBizModel(model);
            AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);

            if (response.isSuccess()) {
                // 返回JSON格式数据给前端
                Map<String, String> result = new HashMap<>();
                result.put("orderInfo", response.getBody());
                return result;
            } else {
                // 处理失败情况
                String diagnosisUrl = DiagnosisUtils.getDiagnosisUrl(response);
                throw new RuntimeException("支付宝支付调用失败，诊断链接: " + diagnosisUrl);
            }
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
    }

    private AlipayConfig getAlipayConfig() {

        AlipayConfig alipayConfig = new AlipayConfig();
        alipayConfig.setServerUrl("https://openapi.alipay.com/gateway.do");
        alipayConfig.setAppId(aliPayProperties.getAppId());
        alipayConfig.setPrivateKey(aliPayProperties.getAppPrivateKey());
        alipayConfig.setFormat(aliPayProperties.getFormat());

        alipayConfig.setAlipayPublicKey(aliPayProperties.getAlipayPublicKey());
        alipayConfig.setCharset("UTF-8");
        alipayConfig.setSignType(aliPayProperties.getSignType());

        return alipayConfig;
    }

}

